// EventBus.js
import { provide, inject } from 'vue';

const createEventBus = () => {
  const listeners = {};

  const on = (event, callback) => {
    if (!listeners[event]) {
      listeners[event] = [];
    }
    listeners[event].push(callback);
  };

  const emit = (event, data) => {
    if (listeners[event]) {
      listeners[event].forEach(callback => {
        callback(data);
      });
    }
  };

  return { on, emit };
};

const EventBusSymbol = Symbol();

export const provideEventBus = () => {
  setTimeout(() => {
    provide(EventBusSymbol, createEventBus());
  }, 0);
};

export const useEventBus = () => {
  const eventBus = inject(EventBusSymbol);
  if (!eventBus) {
    throw new Error('EventBus not provided!');
  }
  return eventBus;
};
